<?php

namespace App\Http\Services;

use App\Http\Helpers\Sign;
use QCloud\Cos\Api;

class AuthService{

    const PREFIX = 'weixin';

    const APPID = "wx9c8038dacb8f46c4";

//    const PC_REDIRECT = DOMAIN . ':' . PORT . '/#/login';
    const PC_REDIRECT = DOMAIN . '/login';
    const H5_REDIRECT = ALIYUN_DOMAIN  . '/mobile/login';

    /**
     *获取用户移动端H5的oauth地址
     * @author: lican<364548233@qq.com>
     */
    public static function getUserH5AuthUri($schoolCode, $appKey){
        $school = SchoolService::getSchoolInfo($schoolCode);
        $params = [
            'app_key' => $appKey,
            'response_type' => 'code',
            'scope' => 'snsapi_sso',
            'ocode' => $schoolCode,
            'redirect_uri' => self::H5_REDIRECT,
            'state' => $schoolCode,
            'connect' => 'curLogin'
        ];
        $url = $school['gate_host'] . ApiService::H5_OAUTH . '?' . http_build_query($params);
        return $url;
    }

    /**
     *获取PC端oauth地址
     * @author: lican<364548233@qq.com>
     */
    public static function getUserPcAuthUri($schoolCode, $appKey){
        $school = SchoolService::getSchoolInfo($schoolCode);
        $params = [
            'app_key' => $appKey,
            'response_type' => 'code',
            'scope' => 'snsapi_sso',
            'ocode' => $schoolCode,
            'redirect_uri' => self::PC_REDIRECT,
            'state' => $schoolCode,
            'connect' => 'curLogin'
        ];
        $url = $school['gate_host'] ?? "https://open.wecard.qq.com" . ApiService::PC_OAUTH . '?' . http_build_query($params);
        return $url;
    }

    /**
     *获取用户信息
     * @author lican<364548233@qq.com>
     */
    public static function getUser(){
        $key = self::PREFIX .'_auth';
        $encrypt = isset($_COOKIE[$key]) && !empty($_COOKIE[$key]) ? $_COOKIE[$key] : '';
        if(empty($encrypt)){
            return [];
        }
        try{
            $data = decrypt($encrypt);
        }catch(\Exception $e){
            Sign::writeLog(__FUNCTION__,  '__data__' . $e->getMessage(), 'auth');
            return [];
        }
        $key = $key . '_' . $data['id'];
        $res = app('redis')->get($key);
        return json_decode($res, true);
    }

    /**
     *保存用户信息
     * @author lican<364548233@qq.com>
     */
    public static function setUser($user){
        $key = self::PREFIX . '_auth';
        $data = [
            'id' => $user['id'],
            'name' => $user['nickname'],
            'login_time' => date('Y-m-d H:i:s', time())
        ];
        setcookie($key, encrypt($data), time() + 86400, '/');
        $key = $key . '_' . $data['id'];
        app('redis')->setex($key, 86400, json_encode($user));
        return true;
    }

}
